package org.esjsoftware.v2m.rim.view;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;

import javax.microedition.media.MediaException;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.FocusChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.DateField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.RadioButtonField;
import net.rim.device.api.ui.component.RadioButtonGroup;

import org.esjsoftware.v2m.rim.audio.AudioPlayer;
import org.esjsoftware.v2m.rim.common.Content;
import org.esjsoftware.v2m.rim.common.Messages;
import org.esjsoftware.v2m.rim.entity.ConfigurationEntity;
import org.esjsoftware.v2m.rim.model.ConfigurationModel;
import org.esjsoftware.v2m.rim.proxy.MessageProxy;
import org.esjsoftware.v2m.rim.ui.FullWidthButton;
import org.esjsoftware.v2m.rim.util.Tools;


/**
 * 
 * @author Ernest
 *
 */
public class HomeScreen extends AbstractScreen {
	private static HomeScreen instance = null;
	EditField phoneNumberEditField;
//	BasicFilteredList phoneNumberBasicFilteredList;
//	AutoCompleteField phoneNumberAutoCompleteFieldContacts;
	FullWidthButton buttonClearRMS;
	FullWidthButton buttonRecordMessage;
	FullWidthButton buttonPlayMessage;
	RadioButtonGroup radioButtonGroup;
	RadioButtonField sendNowRadioButtonField;
	RadioButtonField sendLaterRadioButtonField;
	FullWidthButton buttonSendMessage;
	FullWidthButton buttonMessageStatus;
	DateField sendTime;
	int sendTimeIndex = 0;
//	AudioThread audioThread = new AudioThread();
	AudioPlayer audio = new AudioPlayer();
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	MessageProxy mp = new MessageProxy();
	
	DateField dateField;
	
	public static HomeScreen getInstance(){
		if (instance == null) {
			instance = new HomeScreen();
		}
		return instance;
	}
	
	public HomeScreen () {
		setTitle (Messages.getTITLE_HOME());
		
		phoneNumberEditField = new EditField(Messages.getMSG_TO(), "", Content.getMAX_PHONE_NUMBER_LENGTH() , EditField.FILTER_PHONE);
		phoneNumberEditField.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context){
				if(phoneNumberEditField.getText().length() >= 7){
					buttonRecordMessage.setEditable(true);
				} else {
					buttonRecordMessage.setEditable(false);
					buttonPlayMessage.setEditable(false);
					buttonSendMessage.setEditable(false);
				}
			}
		});
		phoneNumberEditField.setFocusListener(new FocusChangeListener(){
			public void focusChanged(Field fild, int eventType){
				setMenuItem();
			}
		});
		
        add(phoneNumberEditField);
        
        
//        
//		buttonClearRMS = new ButtonField("Clear RMS", ButtonField.NEVER_DIRTY | ButtonField.CONSUME_CLICK);
//		buttonClearRMS.setChangeListener(new FieldChangeListener() {
//            public void fieldChanged(Field field, int context) {
//            	messageDialog("Happy dialog");
//            }
//        });
//		add(buttonClearRMS);
		
//		phoneNumberBasicFilteredList = new BasicFilteredList();
//		phoneNumberBasicFilteredList.addDataSource(0, BasicFilteredList.DATA_SOURCE_CONTACTS,
//                BasicFilteredList.DATA_FIELD_CONTACTS_NAME_FULL | BasicFilteredList.DATA_FIELD_CONTACTS_COMPANY | BasicFilteredList.DATA_FIELD_CONTACTS_EMAIL,
//                BasicFilteredList.DATA_FIELD_CONTACTS_NAME_FULL,
//                BasicFilteredList.DATA_FIELD_CONTACTS_EMAIL,                                    
//                -1,
//                null, 
//                BasicFilteredList.COMPARISON_IGNORE_CASE);
//		// Create AutoCompleteFields
//		phoneNumberAutoCompleteFieldContacts = new AutoCompleteField(phoneNumberBasicFilteredList, AutoCompleteField.LIST_STATIC | AutoCompleteField.LIST_DROPDOWN);
//		add(new LabelField(Messages.getMSG_TO()));
//        add(phoneNumberAutoCompleteFieldContacts);

		buttonRecordMessage = new FullWidthButton(Messages.getMSG_RECORD_MESSAGE());
		buttonRecordMessage.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context){
				popRecordConfirm();
			}
		});
		buttonRecordMessage.setEditable(false);
		add(buttonRecordMessage);
		
		buttonPlayMessage = new FullWidthButton(Messages.getMSG_PLAY_MESSAGE());
		buttonPlayMessage.setChangeListener(new FieldChangeListener(){
			public void fieldChanged(Field field, int context) {
				audio.playAudio();
			}
		});
		buttonPlayMessage.setEditable(false);
		add(buttonPlayMessage);
		
		radioButtonGroup = new RadioButtonGroup();
		sendNowRadioButtonField = new RadioButtonField("Send Now", radioButtonGroup, true);
		sendNowRadioButtonField.setChangeListener(new FieldChangeListener(){
			public void fieldChanged(Field field, int context){
				//selectSendType(0);
			}
		});
		sendLaterRadioButtonField = new RadioButtonField("Send Later", radioButtonGroup, false);
		sendLaterRadioButtonField.setChangeListener(new FieldChangeListener(){
			public void fieldChanged(Field field, int context) {
				//selectSendType(1);
			}
		});
//		radioButtonGroup.setChangeListener(new FieldChangeListener(){
//			public void fieldChanged(Field field, int context) {
//				selectSendType(radioButtonGroup.getSelectedIndex());
//			}
//		});
		add(sendNowRadioButtonField);
		add(sendLaterRadioButtonField);
		
		Date date = new Date();
		sendTime = new DateField("Send Time:", date.getTime(), DateField.DATE_TIME);
		
		add(sendTime);
		sendTimeIndex = sendTime.getIndex();
		//delete(sendTime);
		
		buttonSendMessage = new FullWidthButton(Messages.getMSG_SEND_MESSAGE());
		buttonSendMessage.setChangeListener(new FieldChangeListener(){
			ConfigurationEntity cm = ConfigurationModel.getInstance().getConfiguration();
			public void fieldChanged(Field field, int context) {
				if (radioButtonGroup.getSelectedIndex() == 0) {
					String response = mp.sendMessage(cm.getUserName(), cm.getPassword(), cm.getSender(), phoneNumberEditField.getText(), baos.toByteArray(), "0");
					String[] result = Tools.slipt(response, "##");
					String responseErrorCode = result[0];
					String responseTitle = result[1];
					String responseMessage = result[2];
					messageDialog(responseMessage);
				} else if (radioButtonGroup.getSelectedIndex() == 1) {
					long scheduledTime = sendTime.getDate()/1000;
					Date d = new Date ();
					d.getTime();

					if (scheduledTime < (d.getTime()/1000)) {
						messageDialog("You set an invalid schedule date and time.");
					} else {
						String response = mp.sendMessage(cm.getUserName(), cm.getPassword(), cm.getSender(), phoneNumberEditField.getText(), baos.toByteArray(), "" + scheduledTime);
						String[] result = Tools.slipt(response, "##");
						String responseErrorCode = result[0];
						String responseTitle = result[1];
						String responseMessage = result[2];
						messageDialog(responseMessage);
					}
				}				
			}
		});
		buttonSendMessage.setEditable(false);
		add(buttonSendMessage);
		
		buttonMessageStatus = new FullWidthButton("Message Status");
		buttonMessageStatus.setChangeListener(new FieldChangeListener(){
			public void fieldChanged(Field field, int context){
				getMessageStatus();
			}
		});
		add(buttonMessageStatus);
		
		phoneNumberEditField.setFocus();
		
		this.addMenuItem(_configureMenuItem);
		this.addMenuItem(_messageStatusMenuItem);
		this.addMenuItem(_aboutMenuItem);
	}
	
	public void getMessageStatus(){
		String response = mp.getMessageStatus("12345678910", "123456", "12345678910");
		String[] result = Tools.slipt(response, "##");
		String responseErrorCode = result[0];
		String responseTitle = result[1];
		String responseMessage = result[2];
		messageDialog(responseMessage);
	}
	
	private void selectSendType(int index){
		if (index == 0) {
			System.out.println(">>>>>>>>>>>>>>Send Now");
//			messageDialog("Send Now");
			//sendTime.setEditable(false);
			delete(sendTime);
			System.out.println(">>>>>>>>>>>>>>Send Now2");
		} else if (index == 1){
			System.out.println(">>>>>>>>>>>>>Send Later");
//			messageDialog("Send Later.");
			//sendTime.setEditable(true);
			add(sendTime);
			insert(sendTime, sendTimeIndex);
			System.out.println(">>>>>>>>>>>>>>Send Later2");
		}
	}
	
	private void popRecordConfirm(){
		String[] recordButton = new String[] {Messages.getMSG_RECORD_MESSAGE_BUTTON()};
		if(Dialog.ask(Messages.getMSG_RECORD_MESSAGE_CONTENT(), recordButton, 0) == 0) {
			try {
				audio.record();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (MediaException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			popCancelRecord();
		}
	}
	
	private void popCancelRecord(){
		String[] recordStopButton = new String[] {Messages.getMSG_RECORD_SPEAKING_BUTTON()};
		if(Dialog.ask(Messages.getMSG_RECORD_SPEAKING_CONTENT(), recordStopButton, 0) == 0){
			try {
				audio.recordCommit();
				baos = audio.getAudio();
				hasRecorded();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	private void hasRecorded(){
		if (baos.size() > 0){
			buttonPlayMessage.setEditable(true);
			buttonSendMessage.setEditable(true);
		}
	}
	
	private void setMenuItem(){
		this.addMenuItem(_chooseContactMenuItem);
	}
	
	private MenuItem _chooseContactMenuItem = new MenuItem(Messages.getMSG_MENU_CHOOSE_CONTACT(), 0, 0) {
		public void run() {
			messageDialog("Choose Contact");
		}
	};
	
    private MenuItem _configureMenuItem = new MenuItem(Messages.getMSG_MENU_CONFIGURATION() , 0, 0) {
        public void run() {
//        	UiApplication.getUiApplication().popScreen(ConfigurationScreen.getInstance());
//        	Voice2Mobiles.getInstance().changeScreen();
        }
    };
    
    private MenuItem _messageStatusMenuItem = new MenuItem(Messages.getMSG_MENU_MESSAGE_STATUS(), 0, 0) {
    	public void run() {
    		getMessageStatus();
    	}
    };
    
    private MenuItem _aboutMenuItem = new MenuItem(Messages.getMSG_MENU_ABOUT(), 0, 0) {
    	public void run() {
    		messageDialog(Messages.getMSG_ABOUT());
    	}
    };
}
